<?php

namespace App\Http\Controllers\Api\SmallApp\User;

use App\Http\Controllers\Common\ApiController;
use App\Models\Constant\OrderConstant;
use App\Models\Order\Order;
use App\Models\Setting\SysSetting;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class UserController extends ApiController {

    public function getUserInfo(Request $request) {


        $token = $request->header('token');
        $id = checkJWT($token)['id'];

        $user = User::where(compact('id'))->first();

        if(empty($user))
            return responseFail('未查到有效用户！');
        $user->platform_phone = SysSetting::where('key','platform_phone')->first()->val??'0';

        $countApplyNum = SysSetting::where('key','apply_num')->first()->val??6;

        $countOrder = Order::where('user_id',$id)->whereNotIn('status',OrderConstant::MAP_NOT_EFFECT_APPLY)->count();
        $user->apply_num = $countApplyNum-$countOrder;
        return responseSuccess($user->toArray());

    }

    public function changeCallPhone(Request $request) {
        $phone = $newPhone = $request->input('newPhone');
        $verify_code = $request->input('verify_code');

        $this->validate($request, [
            'newPhone'=>'required|regex:/^1[3456789]\d{9}$/',
            'verify_code'=>'required|Integer',
        ]);

        if(env('APP_ENV')!='local'){
            $key = "verifyCode:$phone:$verify_code";
            if(Redis::exists($key)!=1){
                return responseFail('验证码错误！');
            }
        }

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user))
            return responseFail('未查到有效用户，请先注册！');

        $user->call_phone = $newPhone;
        $user->save();
        return responseSuccess();

    }

    public function changePassword(Request $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('用户无效！');

        $old_password = $request->input('old_password');
        $password = $request->input('password');
        $this->validate($request, [
            'password'=>'required|confirmed|between:8,16|regex:/^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S+$/',
        ],[
            'password.between'=>'密码必须包含数字和字符且8-16位',
            'password.regex'=>'密码必须包含数字和字符且8-16位'
        ]);

        if($user->password!=md5($old_password))
            return responseFail('原密码错误！');
        $user->password = md5($password);
        $user->save();
        return responseSuccess();
    }


}
